package cn.com.yang.log;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * JAVA网络编程
 * @author yangyijin
 * @since 2023.05.13
 */
public class LoggingDaytimeServer {
    public final static int PORT =13;
    private final static Logger auditLogger = Logger.getLogger("requests");
    private final static Logger errorLogger = Logger.getLogger("errors");

    public static void main(String[] args) {
        ExecutorService pool = Executors.newFixedThreadPool(50);
        try(ServerSocket server = new ServerSocket(PORT)){
            while (true){
                try{
                    Socket conn = server.accept();
                    Callable<Void> task = new DayTimeTask(conn);
                    pool.submit(task);
                }catch (IOException e){
                    errorLogger.log(Level.SEVERE,"accept error",e);
                }catch (RuntimeException e){
                    errorLogger.log(Level.SEVERE,"unexpected error "+e.getMessage(),e);
                }
            }
        }catch (IOException ex){
            errorLogger.log(Level.SEVERE,"Couldn't start server",ex);
        }catch (RuntimeException e){
            errorLogger.log(Level.SEVERE,"Could't start server:"+e.getMessage(),e);
        }
    }
    private static class DayTimeTask implements Callable<Void>{
        private Socket conn;
        DayTimeTask(Socket conn){
            this.conn =conn;
        }
        @Override
        public Void call() throws Exception {
            try{
                Date now = new Date();
                //先写入日志，以防万一断开链接
                auditLogger.info(now + " "+conn.getRemoteSocketAddress());
                Writer out = new OutputStreamWriter(conn.getOutputStream());
                out.write(now.toString()+"\r\n");
                out.flush();
            }catch (IOException e){
                //客户端断开连接忽略
            }finally {
                conn.close();
                //忽略
            }
            return null;
        }
    }
}
